import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  CrudExpose,
  ScopeContext,
} from '@fast-crud/fast-crud';

import type { Ref } from 'vue';

import type { ExtendedModalApi } from '@vben/common-ui';
import type { Undefinedable } from '@vben/types';

import type { FormRulesExt } from '#/api';
import type { SopIsvInfoModel } from '#/api/devOperation/sop/model/sopIsvInfoModel';

import { ref } from 'vue';

import { useAccess } from '@vben/access';
import { $t } from '@vben/locales';

import { Button } from 'ant-design-vue';

import { SopIsvInfoApi } from '#/api/devOperation/sop/sopIsvInfo';
import { ActionEnum, DictEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  indexColumn,
  STATE_NUMBER_CONSTANT_DICT,
} from '#/plugins/fast-crud/common';

const { hasPermission } = useAccess();
const permCode = PermCode.basic.open.accessKey;

type ContextRef = {
  showKeysRef: Ref<Undefinedable<ExtendedModalApi>>;
};

export function createCrudOptions(
  props: CreateCrudOptionsProps<SopIsvInfoModel.SopIsvInfoResultVO, ContextRef>,
): CreateCrudOptionsRet<SopIsvInfoModel.SopIsvInfoResultVO> {
  const selectedRowKeys = ref<string[]>([]);
  function handleViewKeys(isvId?: string) {
    props.context?.showKeysRef.value?.setData({
      type: ActionEnum.VIEW,
      isvId,
    });
    props.context?.showKeysRef.value?.open();
  }
  return {
    crudOptions: {
      request: {
        pageRequest: SopIsvInfoApi.openPageRequest,
        addRequest: SopIsvInfoApi.applyForRequest,
        editRequest: SopIsvInfoApi.editOpenRequest,
        delRequest: SopIsvInfoApi.delRequest,
        infoRequest: SopIsvInfoApi.infoRequest,
      },
      actionbar: {
        buttons: {
          add: {
            text: '申请AccessKey',
            show: hasPermission(permCode.add),
          },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            removeFn: SopIsvInfoApi.remove,
            role: permCode.delete,
          }),
        },
      },
      form: {
        col: { span: 24 },
        wrapper: {
          is: 'a-modal',
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: '150px',
        buttons: {
          edit: { show: hasPermission(permCode.edit) },
          view: { dropdown: true, show: true },
          remove: { dropdown: true, show: hasPermission(permCode.delete) },
          copy: { show: false },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        appId: {
          title: $t('devOperation.sop.sopIsvInfo.appId'),
          type: ['text', 'copyable'],
          search: { show: true },
          addForm: {
            show: true,
            component: {
              disabled: true,
              placeholder: '系统自动生成',
            },
          },
          editForm: {
            show: true,
            component: {
              disabled: true,
              placeholder: '系统自动生成',
            },
          },
          column: { width: 250, show: true },
        },
        keys: {
          title: $t('devOperation.sop.sopIsvInfo.keys'),
          type: 'text',
          column: {
            width: 80,
            cellRender({ row }) {
              return (
                <Button
                  block
                  onClick={() => handleViewKeys(row.id)}
                  type="link"
                >
                  查看
                </Button>
              );
            },
          },
          form: {
            show: false,
            submit: false,
          },
        },
        name: {
          title: $t('devOperation.sop.sopIsvInfo.name'),
          type: 'text',
          search: { show: true },
        },
        remark: {
          title: $t('devOperation.sop.sopIsvInfo.remark'),
          type: 'textarea',
          search: { show: false },
          column: { ellipsis: true, showTitle: true },
        },
        expirationTime: {
          title: '有效期',
          type: 'datetimerange',
          search: { show: true },
          addForm: { show: false },
          editForm: { show: false },
          form: {
            component: {
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
            },
          },
          // 表单回显时，处理数据格式
          valueBuilder({ row, key }) {
            if (row && row.startExpirationTime && row.endExpirationTime) {
              row[key] = [row.startExpirationTime, row.endExpirationTime];
            }
          },
          viewForm: {
            ignoreUseCellComponent: true,
            render: (
              context: ScopeContext<SopIsvInfoModel.SopIsvInfoResultVO>,
            ) => {
              const row = context.row;
              if (
                row.startExpirationTime !== null &&
                row.endExpirationTime !== null
              ) {
                return `${row.startExpirationTime}至${row.endExpirationTime}`;
              } else if (
                row.startExpirationTime === null &&
                row.endExpirationTime !== null
              ) {
                return `截止至${row.endExpirationTime}`;
              } else if (
                row.startExpirationTime !== null &&
                row.endExpirationTime === null
              ) {
                return `${row.startExpirationTime}至永久`;
              } else {
                return '永久有效';
              }
            },
          },
          column: {
            customRender: (
              context: ScopeContext<SopIsvInfoModel.SopIsvInfoResultVO>,
            ) => {
              const row = context.record as SopIsvInfoModel.SopIsvInfoResultVO;
              if (
                row.startExpirationTime !== null &&
                row.endExpirationTime !== null
              ) {
                return `${row.startExpirationTime}至${row.endExpirationTime}`;
              } else if (
                row.startExpirationTime === null &&
                row.endExpirationTime !== null
              ) {
                return `截止至${row.endExpirationTime}`;
              } else if (
                row.startExpirationTime !== null &&
                row.endExpirationTime === null
              ) {
                return `${row.startExpirationTime}至永久`;
              } else {
                return '永久有效';
              }
            },
            show: true,
          },
        },
        status: {
          title: $t('devOperation.sop.sopIsvInfo.status'),
          type: 'dict-radio',
          dict: STATE_NUMBER_CONSTANT_DICT,
          search: { show: true },
          addForm: { show: false },
          editForm: { show: false },
          column: { width: 70 },
        },
        auditStatus: {
          title: $t('devOperation.sop.sopIsvInfo.auditStatus'),
          type: 'dict-radio',
          dict: backendDict({ type: DictEnum.AuditStatusEnum }),
          addForm: { show: false },
          editForm: { show: false },
          column: {
            show: true,
            width: 80,
          },
        },
        auditTime: {
          title: $t('devOperation.sop.sopIsvInfo.auditTime'),
          type: 'datetime',
          addForm: { show: false },
          editForm: { show: false },
          column: {
            show: true,
            width: 180,
          },
        },
        submissionTime: {
          title: $t('devOperation.sop.sopIsvInfo.submissionTime'),
          type: 'datetime',
          addForm: { show: false },
          editForm: { show: false },
          column: {
            show: true,
            width: 180,
          },
        },
        reviewComments: {
          title: $t('devOperation.sop.sopIsvInfo.reviewComments'),
          type: 'text',
          search: { show: false },
          addForm: { show: false },
          editForm: { show: false },
          column: {
            show: false,
          },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}

export const frontRules = (
  _crudExpose: CrudExpose,
  _mode: ActionEnum,
): FormRulesExt => {
  return {};
};
